package com.athuiju.fenxiaoback.service.impl;

import com.athuiju.fenxiaoback.entity.TbCart;
import com.athuiju.fenxiaoback.entity.TbCartitem;
import com.athuiju.fenxiaoback.mapper.TbCartitemMapper;
import com.athuiju.fenxiaoback.service.TbCartService;
import com.athuiju.fenxiaoback.service.TbCartitemService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author athuiju
 * @since 2021-07-02
 */
@Service
public class TbCartitemServiceImpl extends ServiceImpl<TbCartitemMapper, TbCartitem> implements TbCartitemService {

    @Autowired
    TbCartService cartService;

    @Autowired
    TbCartitemService cartitemService;

    @Override
    public List<TbCartitem> getUserCheckedCartItems(String memberid) {
        List<TbCartitem> tbCartitems = cartitemService.list(new QueryWrapper<TbCartitem>().eq("memberid", memberid).eq("is_check",1));
        return tbCartitems;
    }



    @Override
    public String calcCheckItemTotalPrice(List<String> skuIds, String memberid) {
        QueryWrapper<TbCartitem> itemWrapper=null;

        QueryWrapper<TbCart> cartWrapper= new QueryWrapper<>();
        cartWrapper.eq("memberid", memberid);
        TbCart cart = cartService.getOne(cartWrapper);


        ArrayList<TbCartitem> items=new ArrayList<>();
        for (int i=0;i<skuIds.size();i++){
            itemWrapper=new QueryWrapper<>();
            itemWrapper.eq("memberid",memberid);
            itemWrapper.eq("skuId",skuIds.get(i));
            TbCartitem cartitem=this.baseMapper.selectOne(itemWrapper);
            items.add(cartitem);
        }
        cart.setItems(items);
        boolean update = cartService.update(cart, cartWrapper);
        if (update){
          return   cart.getTotalAmount().toString();
        }
        return "计算失败";


    }




    public void calcTotalPrice(Long skuId,String memberid){
        QueryWrapper<TbCartitem> wrapper=new QueryWrapper();
        wrapper.eq("skuId",skuId);
        wrapper.eq("memberid",memberid);
        TbCartitem cartitem = this.baseMapper.selectOne(wrapper);

        Long totalPrice=cartitem.getCount() *cartitem.getPrice().longValue();
        cartitem.setTotalPrice(new BigDecimal(totalPrice));

        baseMapper.update(cartitem,wrapper);

    }



}
